package com.frame.work.frame.deal.device0fbe;


import com.alibaba.fastjson.JSONObject;
import com.frame.work.common.base.core.CoreServer;
import com.frame.work.common.constant.Const;
import com.frame.work.common.constant.TypeEnum;
import com.frame.work.common.util.JedisUtil;
import com.frame.work.config.SpringUtil;
import com.frame.work.entity.TblFingerprint;
import com.frame.work.entity.TblSecurityLog;
import com.frame.work.mapper.SelectDeviceMapper;
import com.frame.work.mapper.SelectGatewayMapper;
import com.frame.work.mapper.TblFingerprintMapper;
import com.frame.work.service.TblSecurityLogService;
import com.frame.work.service.impl.JpushService;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Integer.parseInt;

/**
 * 指纹锁_NbIot
 */
@Data
public class ZhiWenSuo_NbIot_0FBE4002 {

    private String deviceMac;
    private String odIndex;
    private String deviceType;
    private String productType;
    private Map actions;


    //private String switchState;
    public ZhiWenSuo_NbIot_0FBE4002(String data) {

        this.setDeviceMac(StringUtils.substring(data, 2, 18));
        this.setOdIndex(StringUtils.substring(data, 18, 22));
        this.setDeviceType(StringUtils.substring(data, 34, 36));
        this.setProductType(StringUtils.substring(data, 36, 38));

        //开门--关门
        String switchState = StringUtils.substring(data, data.length() - 8, data.length() - 6);

        //用户类型，01:管理员，02：普通用户
        String userid = StringUtils.substring(data, data.length() - 16, data.length() - 14);
        //开锁方式，01:指纹，02：密码
        String idType = StringUtils.substring(data, data.length() - 10, data.length() - 8);
        //设备电压占比量   //BCD码，大端，45%  特别说明：01 00-----100%
        String dianya = StringUtils.substring(data, data.length() - 28, data.length() - 24);
        if ("0100".equals(dianya)) {
            dianya = "100";
        } else {
            dianya = StringUtils.substring(dianya, 2, 4);
        }

        String alarm = StringUtils.substring(data, data.length() - 6, data.length() - 4); //提示状态02:防撬，03：低电量

        //将actions信息放入json对象中
        Map<String, Object> actions = new HashMap();
        actions.put("switchState", switchState);
        actions.put("userid", userid);
        actions.put("idType", idType);
        actions.put("dianya", dianya);
        actions.put("alarm", alarm);
        this.setActions(actions);


        //处理好的json对象
        String json = JSONObject.toJSONString(this);
        //将数据发送到mqtt队列中
        //JsonToMqtt.sendMQTT(gatewayMac,json);
        /**
         * 这里有点小问题，就是如果没有网关就没有日志
         */

        String type = TypeEnum.NORMAL.code();
        if ("01".equals(switchState)) {
            SelectDeviceMapper testMapper = (SelectDeviceMapper) SpringUtil.getBean(SelectDeviceMapper.class);
            userid = Integer.toString(parseInt(userid, 16));
            List<Map> list = testMapper.getDevice4(userid, this.getDeviceMac());
            if (list.size() > 0) {
                String homeId = (String) list.get(0).get("home_id");
                String gatewayMac = "";
                if (("01".equals(idType) || "02".equals(idType) || "03".equals(idType) || "04".equals(idType)) && (list.get(0).get("fingerprint_id") == null || list.get(0).get("fingerprint_id") == "")) {
                    //指纹锁表里新增数据
                    TblFingerprint tblFingerprint = new TblFingerprint();
                    tblFingerprint.setDeviceId((String) list.get(0).get("device_id"));
                    tblFingerprint.setNumber(Integer.toString(parseInt(userid, 16)));
                    tblFingerprint.setName("指纹" + Integer.toString(parseInt(userid, 16)));
                    tblFingerprint.setIdType(idType);

                    TblFingerprintMapper tblFingerprintMapper = (TblFingerprintMapper) SpringUtil.getBean(TblFingerprintMapper.class);
                    tblFingerprintMapper.insert(tblFingerprint);
                }
                String homeName = "";
                String content = "";
                String deviceName = (String) list.get(0).get("device_name");
                // 普通密码打开
                if ("07".equals(idType)) {
                    content = homeName + deviceName + "被密码打开";
                    type = TypeEnum.NORMAL.code();
                }
                // 劫持密码打开
                else if ("08".equals(idType)) {
                    content = homeName + deviceName + "被劫持密码打开";
                    type = TypeEnum.WARNING.code();
                }
                // 远程打开
                else if ("0A".equals(idType)) {
                    content = homeName + deviceName + "被远程打开";
                    type = TypeEnum.NORMAL.code();
                }
                //卡片打开
                else if ("0B".equals(idType)) {
                    content = homeName + deviceName + "被卡片打开";
                    type = TypeEnum.NORMAL.code();
                } else if ((String) list.get(0).get("fingerprint_name") == "" || (String) list.get(0).get("fingerprint_name") == null) {
                    content = homeName + deviceName + "被指纹" + parseInt(userid, 16) + "打开";
                    type = TypeEnum.NORMAL.code();
                } else {
                    content = homeName + deviceName + '被' + (String) list.get(0).get("fingerprint_name") + "打开";
                    type = TypeEnum.NORMAL.code();
                }
                //极光推送
                type = TypeEnum.WARNING.code();

                String orgCode = (String) list.get(0).get("organization_code");
                String userId2 = (String) list.get(0).get("user_id");
                String deviceId = (String) list.get(0).get("device_id");
                String sourceId = (String) list.get(0).get("source_id");
                String account = (String) list.get(0).get("account");
                String nickName = (String) list.get(0).get("nick_name");
                String sourceType = Long.toString((long) list.get(0).get("source_type"));
                //极光推送部分（代码存在残缺）


                if (list.get(0).get("source_id") != null && !"".equals(list.get(0).get("source_id"))) {
                    String pushType = "1";
                    String defendStatus = "02";

                    String pushType1 = (String) list.get(0).get("pushType");
                    String defend_status = (String) list.get(0).get("defend_status");
                    if (pushType1 != null && !"".equals(pushType1)) {
                        pushType = (String) list.get(0).get("pushType");
                    }
                    if (defend_status != null && !"".equals(defend_status)) {
                        defendStatus = (String) list.get(0).get("defend_status");
                    }
                    if ("1".equals(pushType) || ("2".equals(pushType) && "01".equals(defendStatus)) || ("3".equals(pushType) && "02".equals(defendStatus))) {

                        JpushService jPushService = (JpushService) SpringUtil.getBean(JpushService.class);
                        try {
                            jPushService.sendNoSave("", content, type, sourceId, Const.MsgType.MSG_WARNING_TYPE, deviceId, userId2, sourceType, orgCode);

                        } catch (Exception e) {

                        }

                    }
                }

                SelectGatewayMapper selectGatewayMapper = (SelectGatewayMapper) SpringUtil.getBean(SelectGatewayMapper.class);
                List<String> gatewaylist = selectGatewayMapper.getGateway(homeId);


                if (gatewaylist.size() > 0) {
                    gatewayMac = gatewaylist.get(0);
                    if ((gatewayMac != null) && (gatewayMac != "")) {


                        //保存报警信息
                        TblSecurityLog tblSecurityLog = new TblSecurityLog();
                        tblSecurityLog.setGatewayMac(gatewayMac);
                        tblSecurityLog.setDeviceMac(this.getDeviceMac());
                        //tblSecurityLog.setCreateTime(new Date());
                        tblSecurityLog.setContent(content);
                        tblSecurityLog.setType(type);
                        //获取userId
                        String userId = (String) list.get(0).get("user_id");
                        tblSecurityLog.setUserId(userId);
                        TblSecurityLogService tblSecurityLogService = (TblSecurityLogService) SpringUtil.getBean(TblSecurityLogService.class);
                        tblSecurityLogService.insert(tblSecurityLog);


                        Integer sceneCode = (Integer) list.get(0).get("scene_code");
                        if (("01".equals(idType) || "02".equals(idType) || "03".equals(idType) || "04".equals(idType)) && sceneCode != null) { // 场景不为空
                            // 场景触发
                            CoreServer coreServer = (CoreServer) SpringUtil.getBean(CoreServer.class);
                            JedisUtil jedisUtil = (JedisUtil) SpringUtil.getBean(JedisUtil.class);
                            Jedis jedis = jedisUtil.getJedis();
//                            coreServer.writeDataToGateWay(gatewayMac, FrameMaker.getWriteGateway50SceneTrigger09Frame(gatewayMac, sceneCode), jedis);
                        }
                    }
                }
            }
        }
    }
}
